
<script setup lang="ts">
import type { CommentList } from '../../typings';
import { useRouter } from 'vue-router';
import { Api } from '../../assets/api';
import { onMounted, ref, watch, computed } from 'vue';
import CommentComp from '../../components/CommentComps/CommentComp.vue'
import LoadingComp from '@/components/LoadingComp/LoadingComp.vue';
const router = useRouter()
const props = defineProps<{
    list: string,
}>()
const currentList = computed(() => {
    return JSON.parse(props.list)
})

console.log(currentList.value);
let currentVideoUrl = ref()
let currentVideoUrlComp = computed(() => {
    return currentVideoUrl.value
})


let likePics = ref<Array<string>>()
let hotLink = ref<Array<string>>()
const getPics = async () => {
    let { data } = await Api.getVideoViewPic(currentList.value.itemId, currentList.value.actorId)
    console.log(data.data);
    likePics.value = data.data.likePics
    hotLink.value = data.data.hotLink.avatars

}

onMounted(() => {
    getPics()
    currentVideoUrl.value = currentList.value.videoUrl
})

watch(() => currentList.value.videoUrl, (n, o) => {
    if (n != o) {
        commentsData.value = []
        currentVideoUrl.value = n
        // console.log( currentVideoUrl.value);
        video.value.src = n
        video.value.currentTime = 0
        currrentTime.value = 0
        progress.value.style.width = 0
        totalComment.value = 0
        getPics()
        getComments()
    }
})

// 相关播放状态<
let timer = ref(null)
//是否是一第一次播放
let limine = ref<boolean>(false)
// 播放视频
let isPlay = ref<boolean>()
// 获取视频dom
const video = ref()
// 改变播放状态
const changeIsPlay = () => {
    isPlay.value = !isPlay.value

}
// 监听播放状态,视频随着播放状态而改变
watch(() => isPlay.value, (n) => {
    if (n) {
        video.value.play()

        totleTime.value = setDurration(video.value.duration)
        setCurrentTime()
        limine.value = true
        timer.value = setTimeout(() => {
            limine.value = false

        }, 3000)

    } else {
        video.value.pause()
        clearInterval(interTime.value)
        interTime.value = null
        clearTimeout(timer.value)
        timer.value = null
    }
})

watch(() => limine.value, (n) => {
    if (n) {
        if (isPlay.value) {
            if (timer.value != null) {
                clearTimeout(timer.value)
                timer.value = null
            }
            timer.value = setTimeout(() => {
                limine.value = false
                // console.log(limine.value);

            }, 3000)
        }
    }
})
const totleTime = ref<string>('')
const setDurration = (duration: number) => {
    // console.log(duration);
    let m = duration / 60 >= 10 ? parseInt(('0' + duration / 60)) : '0' + parseInt(('0' + duration / 60) as string)
    let s = duration % 60 >= 10 ? parseInt(('0' + duration % 60)) : '0' + parseInt(('0' + duration % 60) as string)


    return `${(m)}:${s}`
}
let interTime = ref(null)
let currrentTime = ref(0)
const progress = ref()
const setCurrentTime = () => {
    clearInterval(interTime.value)
    interTime.value = null
    if (isPlay) {
        interTime.value = setInterval(() => {
            if (parseInt(progress.value.style.width) >= 230) {
                progress.value.style.width = 230.8 + 'px'
                clearInterval(interTime.value)
                interTime.value = null
                isPlay.value = false
                video.value.currentTime = 0
            }
            currrentTime.value = video.value.currentTime

            progress.value.style.width = (video.value.currentTime / video.value.duration) * 230.8 + 'px'

        }, 1000)
    }

}

const currrentTimeComp = computed(() => {

    let m = currrentTime.value / 60 >= 10 ? parseInt(('0' + currrentTime.value / 60)) : '0' + parseInt(('0' + currrentTime.value / 60) as string)
    let s = currrentTime.value % 60 >= 10 ? parseInt(('0' + currrentTime.value % 60)) : '0' + parseInt(('0' + currrentTime.value % 60) as string)

    return `${m}:${s}`

})
// 相关播放状态>

// 拖动事件<
let spot = ref()
const dragFn = (e: any) => {
    limine.value = true
    // console.log(e.changedTouches[0].pageX);
    clearInterval(interTime.value)
    interTime.value = null
    let num = e.changedTouches[0].pageX - 32
    if (e.changedTouches[0].pageX - 32 >= 230.8) {
        num = 230.8
    }
    progress.value.style.width = num + 'px'
    e.target.ontouchend = () => {
        video.value.currentTime = (((e.changedTouches[0].pageX - 32) / 230) * video.value.duration).toFixed(0)
        currrentTime.value = video.value.currentTime
        setCurrentTime()

    }
}
// 拖动事件>

// 评论<
let showPopup = ref(false)
let commentsData = ref<Array<CommentList>>([])
let totalComment = ref<number>(0)
let showLoading = ref(false)
let currentPage = ref(0)
// 获取评论
const getComments = async (page = 1) => {
    showLoading.value = true
    let { data } = await Api.getVideoComments(currentList.value.itemIdUrl, currentList.value.actorIdUrl, page)
    data.data?.commentList.map(item => {
        commentsData.value.push(item)
    })

    let obj = localStorage.commentList ? JSON.parse(localStorage.commentList) : []
    obj.map(t => {
        if (t.id == currentList.value.itemId) {
            commentsData.value.unshift(t)
        }
    })

    totalComment.value = data.data?.total
    console.log(commentsData.value);
    showLoading.value = false
    currentPage.value = page

}

const changesPopup = () => {

    showPopup.value = !showPopup.value

}
// 评论滚动监听
const commentScroll = (e) => {

    if (e.target.scrollTop >= 1930 * currentPage.value && currentPage.value * 20 < totalComment.value) {

        if (!showLoading.value) {
            console.log(currentPage.value + 1);
            // console.log(e.target.scrollTop);

            getComments(currentPage.value + 1)
        }
    }

}


onMounted(() => {
    getComments()
})

// 发表评论
let inputVal = ref()
const currentCommentTime = computed(() => {
    let data = new Date()
    let M = data.getMonth() + 1 >= 10 ? data.getMonth() + 1 : '0' + (data.getMonth() + 1)
    let d = data.getDate() >= 10 ? data.getDate() : '0' + data.getDate()
    let h = data.getHours() >= 10 ? data.getHours() : '0' + data.getHours()
    let m = data.getMinutes() >= 10 ? data.getMinutes() : '0' + data.getMinutes()

    return `${M}/${d}  ${h}:${m}`

})
const addComments = () => {
    let obj = localStorage.commentList ? JSON.parse(localStorage.commentList) : []
    obj.push({
        avatar: 'http://s10.mogucdn.com/new1/v1/bdefaultavatar/02.jpg_160x160.jpg',
        content: inputVal.value,
        time: currentCommentTime.value,
        userName: sessionStorage.token,
        commentId: Date.now(),
        id: currentList.value.itemId
    })

    localStorage.commentList = JSON.stringify(obj)
    commentsData.value.unshift({
        avatar: 'http://s10.mogucdn.com/new1/v1/bdefaultavatar/02.jpg_160x160.jpg',
        content: inputVal.value,
        time: currentCommentTime.value,
        userName: sessionStorage.token,
        commentId: Date.now(),
        id: currentList.value.itemId
    })
    inputVal.value = ''

}

// 评论>


const goToShoppingCart = () => {
    router.push('/shoppingcart')
}
const goToProductDetails = () => {
    router.push({
        name: 'productdetails',
        params: {
            id: currentList.value.itemIdUrl
        }
    })
}

const goToLiveView = ()=>{
    router.push('/live')
}
const isStar = ref(false)
</script>

<template>
    <div class="video flex flex-col">

        <div class="video-list relative">

            <div class="mask absolute left-0 top-0 w-full h-full"
                style="background-image: linear-gradient(180deg,transparent,rgba(0,0,0,.02) 18%,rgba(0,0,0,.2));">

            </div>


            <video ref="video" @click="limine = !limine">
                <source :src="currentVideoUrlComp" type="video/mp4">
                <!-- <source src="movie.ogg" type="video/ogg"> 您的浏览器不支持Video标签。 -->
            </video>

            <!-- 屏幕中间的播放按钮 -->
            <div class="play-btn absolute left-1/2 top-1/2" style="transform: translate(-50%,-50%);z-index: 2;">
                <van-icon @click="changeIsPlay" v-show="!isPlay" name="play-circle-o" size="50px" color="#eee" />
            </div>

            <!-- 右边功能 -->
            <div style="z-index: 1;transform: translateY(-20%);"
                class=" px-2 text-sm right-icon absolute right-0 top-1/2 w-16 h-2/5 flex flex-col justify-between items-center text-white">
                <img class=" rounded-full" :src="currentList.actorAvatar" alt="">
                <span class="flex flex-col items-center">
                    <van-icon v-show="!isStar" @click="isStar = !isStar" name="star" size="30" />
                    <van-icon v-show="isStar" @click="isStar = !isStar" name="star" color="#ff4466" size="30" />

                    收藏
                </span>
                <span class="flex flex-col items-center" style="z-index: 2;" @click="changesPopup">
                    <van-icon name="chat" size="30" />
                    {{ totalComment }}
                </span>
                <span class="flex flex-col items-center" @click="goToShoppingCart">
                    <van-icon name="cart" size="30" />
                    购物车
                </span>

            </div>

            <!-- 上面热门直播 -->
            <div @click="goToLiveView" class="hot-live w-40 pl-1.5  flex items-center text-white absolute left-0 top-0 rounded-full"
                style="background-color: rgba(0,0,0,.4); transform: translate(5%,50%);">

                <div class="img-list w-2/5  flex">
                    <img class=" w-8 h-8 rounded-full relative left-0 top-0" v-for="h in hotLink" :key="h" :src="h" alt="">
                </div>

                <span class="ml-1">
                    热门直播 >
                </span>

            </div>


            <!-- 主播信息 -->
            <div class="host-information absolute bottom-0">

                <div class="comment">

                </div>

                <div class="actor-name">
                    @{{ currentList.actorName }}
                </div>

                <div @click="goToProductDetails" class="sp flex justify-between items-center mt-4 p-2"
                    style="background-color: rgba(0,0,0,.5);">

                    <div class="img-div">
                        <img class=" w-12 h-12" :src="currentList.itemImage" alt="">
                    </div>

                    <div class="sp-title w-3/5 ml-1">

                        <span class=" w-full block overflow-hidden text-ellipsis whitespace-nowrap">{{ currentList.title
                        }}</span>

                        <div class="flex items-center">
                            <span class="p-0.5 text-xs" style=" background: linear-gradient(150deg,#fb872c,#fc4441);">
                                待秒杀
                            </span>
                            <span class="ml-1 font-bold text-lg text-red-500">
                                ￥{{ currentList.showDiscountPrice }}
                            </span>

                        </div>

                    </div>

                    <div class="btn rounded-full px-2 py-1 " style="background-color: #ff4466;">
                        立即购买
                    </div>

                </div>

                <div v-show="limine" class="progress-bar mt-2 flex justify-between items-center">
                    <van-icon @click="changeIsPlay" name="play" v-show="!isPlay" size="22" />
                    <van-icon @click="changeIsPlay" name="pause" v-show="isPlay" size="22" />
                    <div class="bar relative  h-1 bg-white" style="width: 65%;">
                        <div ref="progress" class="progress absolute left-0 top-0 h-full bg-blue-500">

                            <div @touchmove="dragFn" ref="spot" style="transform: translate(50%,-50%);"
                                class="spot absolute right-0 top-0 w-4 h-4 rounded-full bg-white z-10">

                            </div>

                        </div>
                    </div>

                    <div class="time-div">

                        {{ currrentTimeComp }}/{{ totleTime }}


                    </div>

                </div>


            </div>


            <!-- 评论弹出层 -->
            <div class="popup">
                <van-popup v-model:show="showPopup" :overlay="false" closeable position="bottom"
                    :style="{ height: '60%' }" />

                <!-- 自定义图标 -->
                <van-popup v-model:show="showPopup" :overlay="false" closeable close-icon="close" position="bottom"
                    :style="{ height: '60%' }" />
                <!-- 图标位置 -->
                <van-popup v-model:show="showPopup" :overlay="false" closeable close-icon-position="top-right"
                    position="bottom" :style="{ height: '60%' }">
                    <span class="p-4 block">
                        购买评论 {{ totalComment }}
                    </span>

                    <div class="comment-list h-4/5 overflow-auto relative pb-9" @scroll="commentScroll">



                        <CommentComp v-for="c in commentsData" :key="c.commentId" :list="c"></CommentComp>


                        <van-loading v-show="showLoading && commentsData.length != 0" class=" text-center"
                            color="#0094ff" />
                        <LoadingComp v-show="commentsData.length == 0" :type="1"></LoadingComp>
                    </div>

                    <div class=" w-full input-div fixed bottom-0 px-5  py-4 bg-white">
                        <input @keyup.enter="addComments" v-model.trim="inputVal"
                            class=" w-full  px-1 py-1 bg-gray-200 rounded-full " type="text" placeholder="请输入评论内容">
                    </div>
                </van-popup>
            </div>

        </div>


    </div>
</template>


<style lang="scss" scoped>
.video {
    width: 100vw;
    // height: 100vh;
    background-color: #000;
    overflow-y: auto;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 10;

    video {
        width: 100vw;
        height: 100vh;
    }

    .img-list {
        img {
            border: 1px solid #ccc;

            &:nth-child(2) {
                left: -23px;
            }

            &:last-child {
                left: -40px;
            }
        }
    }

    .host-information {
        width: 100%;
        height: 35vh;
        padding: 10px;
        color: #fff;
        // z-index: 1;

        .comment {
            min-height: 10vh;
        }
    }
}
</style>